<?php


namespace App\Api\Controllers;


use App\Models\Product;
use App\Models\UserFan;
use App\Models\UserFav;
use App\Models\UserFeedback;
use App\Models\UserHistory;
use App\Models\UserLevel;
use App\Models\UserLiveApply;
use App\Models\UserMessage;
use App\Models\UserMoneyLog;
use App\Models\UserPost;
use App\Models\UserScoreLog;
use App\User;
use App\Models\Sms;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use JWTAuth;

class UserController extends Controller
{
    public function paypass(Request $request)
    {
        $user = auth()->user();
        if (!$request->paypass) {
            return $this->responseFailed('paypass必传');
        }
        if (empty($user)) {
            return $this->responseFailed('token过期');
        }
        $user->paypass = encrypt($request->paypass);
        if ($user->save()) {
            return $this->responseSuccess();
        }
        return $this->responseFailed();
    }

    public function findPaypss(Request $request)
    {
        if (!preg_match('/^1[3456789]\d{9}$/', $request->mobile)) {
            return $this->responseFailed('手机号码格式不正确');
        }
        if (!$request->code) {
            return $this->responseFailed('验证码错误');
        }
        if (!$request->paypass) {
            return $this->responseFailed('paypass必传');
        }
        $sms = Sms::where(['mobile'=>$request->mobile])
            ->orderBy('id', 'desc')->first();
        if(!$sms){
            return $this->responseFailed('手机号码输入不正确');
        }
        if($sms->code != $request->code){
            return $this->responseFailed('验证码输入不正确');
        }
        $user = auth()->user();
        if (empty($user)) {
            return $this->responseFailed('token过期');
        }
        if ($user['mobile'] != $request->mobile) {
            return $this->responseFailed('手机号码错误');
        }
        $user->paypass = encrypt($request->paypass);
        if ($user->save()) {
            return $this->responseSuccess();
        }
        return $this->responseFailed();
    }

    //资金明细
    public function moneyLog(Request $request)
    {
        $user = auth()->user();
        /*
        if (!$user) {
            return $this->responseFailed('登录超时');
        }*/
        $where = [
            ['user_id', '=', $user['id']],
        ];
        if ($request->type == 1) {
            $where[] = ['type', '=', 1];
        }
        if ($request->type == 2) {
            $where[] = ['type', '=', 2];
        }
        $log = UserMoneyLog::where($where)->paginate(10)->toArray();
        $log['money'] = $user['money'];
        return $this->responseData($log);
    }

    //积分明细
    public function scoreLog()
    {
        $user = auth()->user();
        $where = [
            ['user_id', '=', $user['id']],
        ];
        $log = UserScoreLog::where($where)->paginate(10)->toArray();
        $log['score'] = $user['score'];
        return $this->responseData($log);
    }

    //加关注 取消关注
    public function optfuns(Request $request)
    {
        $user = auth()->user();
        if (!$request->follow_id) {
            return $this->responseFailed('关注ID必传');
        }
        if (!isset($request->status)) {
            return $this->responseFailed('关注状态必传');
        }
        $where = [
            ['user_id', '=', $user['id']],
            ['follow_id', '=', $request->follow_id],
        ];
        $fans = UserFan::where($where)->first();
        if(!$fans){
            $fans = new UserFan();
            $fans->user_id = $user['id'];
            $fans->follow_id = $request->follow_id;
        }
        $fans->status = $request->status;
        if($fans->save()){
            return $this->responseSuccess();
        }
        return $this->responseFailed();
    }
    //粉丝列表
    public function fans()
    {
        $user = auth()->user();
        $where = [
            ['follow_id', '=', $user['id']],
            ['status', '=', '1'],
        ];
        $follows = UserFan::where($where)
            ->paginate(10)
            ->toArray();
        foreach ($follows['data'] as $key => &$val) {
            $fansUser = User::find($val['user_id']);
            if($fansUser){
                $val['user'] = $fansUser->toArray();
                $where = [
                    ['user_id', '=', $user['id']],
                    ['follow_id', '=', $fansUser['id']],
                    ['status', '=', '1'],
                ];
                $followUser = UserFan::where($where)->first();
                $is_each_follow = 0;
                if ($followUser) {
                    $is_each_follow = $followUser['status'] == 1 ? 1 : 0;
                }
                $val['is_each_follow'] = $is_each_follow;
            } else {
                unset($follows['data'][$key]);
            }
        }
        return $this->responseData($follows);
    }

    //关注列表
    public function follow()
    {
        $user = auth()->user();
        $where = [
            ['user_id', '=', $user['id']],
            ['status', '=', '1'],
        ];
        $follows = UserFan::where($where)
            ->paginate(10)
            ->toArray();
        foreach ($follows['data'] as $key => &$val) {
            $user = User::find($val['follow_id']);
            if($user){
                $val['user'] = $user->toArray();
            } else {
                unset($follows['data'][$key]);
            }
        }
        return $this->responseData($follows);
    }

    //添加浏览记录
    public function addhistory(Request $request)
    {
        $user = auth()->user();
        if (!$request->link_id) {
            return $this->responseFailed('记录ID必传');
        }
        if (!$request->type) {
            return $this->responseFailed('type必传');
        }
        $where = [
            ['user_id', '=', $user['id']],
            ['link_id', '=', $request->link_id],
            ['type', '=', $request->type],
        ];
        $history = UserHistory::where($where)->first();
        if ($history) {
            return $this->responseFailed('已经收藏');
        }
        $history = new UserHistory();
        $history->user_id = $user['id'];
        $history->link_id = $request->link_id;
        $history->type = $request->type;
        if ($history->save()) {
            return $this->responseSuccess();
        }
        return $this->responseFailed();
    }
    //浏览记录列表
    public function history(Request $request)
    {
        if (!$request->type) {
            return $this->responseFailed('type必传');
        }
        $user = auth()->user();
        $where = [
            ['user_id', '=', $user['id']],
            ['type', '=', $request->type],
        ];
        $histroy = UserHistory::where($where)
            ->paginate(10)
            ->toArray();
        foreach ($histroy['data'] as $key=>&$val) {
            if($request->type == 1){
                $val['item'] = UserPost::getOne($val['link_id']);
            }
            if($request->type == 4){
                $val['item'] = Product::getOne($val['link_id']);
            }
        }
        return $this->responseData($histroy);
    }

    //会员等级列表
    public function level()
    {
        $levels = UserLevel::all()->toArray();
        return $this->responseData($levels);
    }

    //直播申请
    public function apply(Request $request)
    {

        $input = $request->only([
            'real_name',
            'card_id',
            'mobile',
            'card_img1',
            'card_img2',
        ]);
        $message = [
            'real_name.required' => '真实姓名必填',
            'card_id.required' => '身份证必填',
            'mobile.required' => '手机号必填',
            'card_img1.required' => '身份证正面必填',
            'card_img2.required' => '身份证反面必填',
        ];
        $validator = Validator::make($input, [
            'real_name' => 'required',
            'card_id' => 'required',
            'mobile' => 'required',
            'card_img1' => 'required',
            'card_img2' => 'required',
        ],$message);
        if ($validator->fails()) {
            return $this->responseFailed($validator->errors()->first());
        }
        $user = auth()->user();
        $result = UserLiveApply::where('user_id', $user['id'])->first();
        if ($result) {
            return $this->responseFailed('已经提交');
        }
        $apply = new UserLiveApply();
        $input['user_id'] = $user['id'];
        foreach ($input as $key=>$val) {
            $apply->$key = $val;
        }
        if ($apply->save()) {
            return $this->responseSuccess();
        }
        return $this->responseFailed();
    }

    //用户中心
    public function info()
    {
        $user = auth()->user();
        $data = [];
        if ($user) {
            $data['user'] = $user->toArray();
            $data['follow'] = UserFan::getFollowCount($user['id']); //关注数
            $data['fans'] = UserFan::getFansCount($user['id']); //粉丝数
            $data['favs'] = UserFav::getFavCount($user['id']); //收藏数
            $data['posts'] = UserPost::getUserPostCount($user['id']); //发布数
        }

        return $this->responseData($data);
    }

    //收藏列表
    public function favs()
    {
        $user = auth()->user();
        $where = [
            ['user_id', '=', $user['id']],
        ];
        $favs = UserFav::where($where)->paginate(10)->toArray();
        foreach ($favs['data'] as $key=>&$val) {
            $post = UserPost::getOne($val['link_id']);
            if ($post) {
                $val['post'] = $post;
            } else {
                unset($favs['data'][$key]);
            }
        }
        return $this->responseData($favs);
    }

    //发布列表
    public function posts()
    {
        $user = auth()->user();
        $where = [
            ['user_id', '=', $user['id']],
        ];
        $posts = UserPost::getPageList($where);
        return $this->responseData($posts);
    }

    //让人中心
    public function otherInfo(Request $request)
    {
        $input = $request->only([
            'user_id',
        ]);
        $validator = Validator::make($input, [
            'user_id' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->responseFailed($validator->errors()->first());
        }
        $user = User::find($input['user_id']);
        if (!$user) {
            return $this->responseFailed('用户不存在');
        }
        $data = [];
        $data['user'] = $user->toArray();
        $data['follow'] = UserFan::getFollowCount($input['user_id']);
        $data['fans'] = UserFan::getFansCount($input['user_id']);
        $data['up_and_fav'] = UserPost::getFeildCount($input['user_id'],'up_num') + UserPost::getFeildCount($input['user_id'],'fav_num');
        $user = auth()->user();
        $data['is_each_follow'] = UserFan::isEachFollow($user['id'], $input['user_id']);
        $where = [
            ['user_id', '=', $user['id']],
        ];
        $data['posts'] = UserPost::getPageList($where);
        return $this->responseData($data);
    }

    //推荐关注列表
    public function recommend()
    {
        $data = UserFan::getPageList();
        return $this->responseData($data);
    }

    //系统消息
    public function messages()
    {
        $data = UserMessage::getPageList();
        return $this->responseData($data);
    }

    //意见反馈
    public function feedback(Request $request)
    {
        if (!$request->bref) {
            return $this->responseFailed('问题描述必填');
        }
        if (!$request->contact) {
            return $this->responseFailed('联系方式必填');
        }
        $user = auth()->user();
        $feedback = new UserFeedback();
        $feedback->bref = $request->bref;
        $feedback->user_id = $user['id'];
        $feedback->contact = $request->contact;
        if ($feedback->save()) {
            return $this->responseSuccess();
        }
        return $this->responseFailed();
    }

    public function logout()
    {
        JWTAuth::parseToken()->invalidate();
        return $this->responseSuccess();
    }
}